#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
from threading import Thread

from scapy.all import sniff, get_if_list, sendp, Packet
from scapy.all import *
from scapy.all import Ether, TCP
from NDN_header_Interest import NDNInterest
from NDN_header_Data_v import NDNData
import hashlib
import binascii

# ifname = "enp7s0f1"
ifname = "h1-eth0"
TYPE_NDN = 0x8624
content = 'Hello, world!'
content_hex = int(binascii.b2a_hex(content), 16)


def get_if():
    ifs = get_if_list()
    iface = None
    for i in get_if_list():
        if ifname in i:
            iface = i
            break
    if not iface:
        print ("Cannot find ifname interface")
        exit(1)
    return iface


def handle_pkt(pkt):
    iface = ifname
    print("got a packet")
    print(type(pkt[Ether].dst))
    if (pkt[Ether].type == 0x8624 and pkt[Ether].dst == "ff:ff:ff:ff:ff:ff"):
        print("got a NDN packet")
        if NDNInterest in pkt and pkt[NDNInterest].TLV_0_Type == 5:
            print("got a interest")
            pkt.show2()
            print("sending data packet")
            print(type(pkt.Component1))
            print(pkt.Component1)
            name_long1 = pkt.Component1
            name_long2 = pkt.Component2
            name_long3 = pkt.Component3
            # name_long4 = pkt[NDNInterest].Component4
            s = hashlib.sha256('')
            s.update(binascii.a2b_hex(hex(name_long1)[2:-1]))
            s.update(binascii.a2b_hex(hex(name_long2)[2:-1]))
            s.update(binascii.a2b_hex(hex(name_long3)[2:-1]))
            # s.update(binascii.a2b_hex(hex(name_long4)[2:-1]))
            s.update(content)
            # print(s)
            signature_value = long(s.hexdigest(), 16)
            print("sending {} on interface {}".format('data', iface))
            bind_layers(Ether, NDNData, type=TYPE_NDN)
            pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
            pkt = pkt / NDNData(Component1=name_long1, Component2=name_long2,
                                Component3=name_long3,
                                Content=content_hex, Signature_Value=signature_value)
            sendp(pkt, iface=iface, verbose=False)
            #        hexdump(pkt)
            #        print "len(pkt) = ", len(pkt)
            # sys.stdout.flush()


def sniffpkt():
    bind_layers(Ether, NDNInterest, type=TYPE_NDN)
    ifaces = list(filter(lambda i: ifname in i, os.listdir(
        '/sys/class/net/')))  # 迭代器i是入口参数，'eth' in i是函数体，从os.listdir('/sys/class/net/')中过滤出满足函数体的部分
    iface = ifaces[0]  # 返回第一个iface 即eth0
    print("sniffing on %s" % iface)
    sys.stdout.flush()  # 刷新缓冲区
    sniff(iface=iface,
          prn=lambda x: handle_pkt(x))  # 流量监控


def main():
    t1 = Thread(target=sniffpkt)
    t1.start()


if __name__ == '__main__':
    main()